package com.app.mvc.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.app.mvc.dao.CategoryDao;
import com.app.mvc.dao.DealDao;
import com.app.mvc.dao.LocationDao;
import com.app.mvc.dao.impl.CategoryDaoImpl;
import com.app.mvc.dao.impl.DealDaoImpl;
import com.app.mvc.dao.impl.LocationDaoImpl;
import com.app.mvc.model.Category;
import com.app.mvc.model.Deal;
import com.app.mvc.model.Location;

public class IndexController extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		DealDao deda = new DealDaoImpl();

		// PAGE NAVIGATION
		int count = deda.numsDeal();
		int k = 1;
		int num = 2;
		int page = 0;
		int temp = 0;
		while (k < count) {
			page = count / num;
			temp = count % num;
			k++;
		}
		if (temp > 0 && temp < num) {
			page++;
		}
		List<Integer> pageNav = new ArrayList<>();
		for (int i = 1; i <= page; i++) {
			pageNav.add(i);
		}

		// GET ALL THE DEAL IN DB
		List<Deal> allDeal = deda.newDeal();

		// VIEW THE DEAL THAT POSITION IS FIRST
		List<Deal> deals = new ArrayList<Deal>();
		Deal ddeal = null;
		if (allDeal.size() > 0) {
			for (Deal deal : allDeal) {
				if (deal.getPosition().equals("first")
						|| deal.getPosition().equalsIgnoreCase("first")) {
					ddeal = new Deal(deal.getTitle(), deal.getPrice(),
							deal.getPercentage(), deal.getShort_content(),
							deal.getLong_content(), deal.getCount_down(),
							deal.getStatus(), deal.getPosition(),
							deal.getImage(), deal.getCategory());
					ddeal.setId(deal.getId());
				} else {
					deals.add(deal);
				}
			}
		}
		
		//PAGE NAVIGATION
		List<Deal> dealPage = deda.getDealByPage(0, num);
		int pageNext = 0;
		int pagePrevious = 0;
		int pageFirst = 0;
		int pageLast = page;
		if (request.getRequestURI().equals(
				"/deal-app-servlet-jsp-mvc2/index.html")) {
			pageNext = 2;
			request.setAttribute("pagePrevious", pagePrevious);
			request.setAttribute("pageFirst", pageFirst);
			request.setAttribute("pageLast", pageLast);
		}

		// SEND TO VIEW
		request.setAttribute("first", ddeal);
		request.setAttribute("deals", dealPage);
		request.setAttribute("pageNav", pageNav);
		request.setAttribute("pageNext", pageNext);
		// ATTACH VIEW
		RequestDispatcher view = request.getRequestDispatcher("jsp/index.jsp");
		view.forward(request, response);
	}
}
